package com.example.mq.demo.controller;

import com.example.mq.demo.model.Message;
import com.example.mq.demo.producer.MessageProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
@RequestMapping("/api/messages")
public class MessageController {

    @Autowired
    private MessageProducer messageProducer;

    @PostMapping("/send")
    public String sendMessage(@RequestBody Message message) {
        message.setId(UUID.randomUUID().toString());
        message.setTimestamp(System.currentTimeMillis());
        messageProducer.sendMessage(message, "normal-topic");
        return "普通消息发送成功";
    }

    @PostMapping("/send-sync")
    public String sendSyncMessage(@RequestBody Message message) {
        message.setId(UUID.randomUUID().toString());
        message.setTimestamp(System.currentTimeMillis());
        messageProducer.sendSyncMessage(message, "sync-topic");
        return "同步消息发送成功";
    }

    @PostMapping("/send-async")
    public String sendAsyncMessage(@RequestBody Message message) {
        message.setId(UUID.randomUUID().toString());
        message.setTimestamp(System.currentTimeMillis());
        messageProducer.sendAsyncMessage(message, "async-topic");
        return "异步消息发送成功";
    }

    @PostMapping("/send-delay")
    public String sendDelayMessage(@RequestBody Message message) {
        message.setId(UUID.randomUUID().toString());
        message.setTimestamp(System.currentTimeMillis());
        messageProducer.sendDelayMessage(message, "delay-topic", 3); // 延迟级别3，约等于10s
        return "延迟消息发送成功";
    }

    @PostMapping("/send-ordered")
    public String sendOrderedMessage(@RequestBody Message message) {
        message.setId(UUID.randomUUID().toString());
        message.setTimestamp(System.currentTimeMillis());
        messageProducer.sendOrderedMessage(message, "ordered-topic", message.getId()); // 使用消息ID作为分片键
        return "顺序消息发送成功";
    }

    @PostMapping("/send-tx")
    public String sendTransactionMessage(@RequestBody Message message) {
        message.setId(UUID.randomUUID().toString());
        message.setTimestamp(System.currentTimeMillis());
        messageProducer.sendTransactionMessage(message, "tx-topic");
        return "事务消息发送成功";
    }
}